let currentRepoId = null;

// 页面加载完成后初始化
$(document).ready(function() {
    loadRepositories();
    
    // 文件上传区域事件
    const uploadArea = document.getElementById('uploadArea');
    if (uploadArea) {
        uploadArea.addEventListener('click', () => {
            document.getElementById('fileInput').click();
        });
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });
    }
    
    // 文件输入事件
    $('#fileInput').on('change', function(e) {
        handleFiles(e.target.files);
    });
});

// 加载仓库列表
function loadRepositories() {
    $.get('/api/repositories', function(repos) {
        const container = $('#repositoryList');
        container.empty();
        
        repos.forEach(repo => {
            const card = createRepositoryCard(repo);
            container.append(card);
        });
    });
}

// 创建仓库卡片
function createRepositoryCard(repo) {
    return `
        <div class="col-md-4 mb-3">
            <div class="card repo-card" onclick="openRepository('${repo.id}', '${repo.name}')">
                <div class="card-body">
                    <h5 class="card-title">
                        <i class="fas fa-folder text-primary"></i>
                        ${repo.name}
                    </h5>
                    <p class="card-text text-muted">${repo.description || '无描述'}</p>
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="fas fa-${repo.visibility === 'public' ? 'unlock' : 'lock'}"></i>
                            ${repo.visibility === 'public' ? '公开' : '私有'}
                        </small>
                        <small class="text-muted">${new Date(repo.created_at).toLocaleDateString()}</small>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// 创建仓库
function createRepository() {
    const formData = {
        name: $('input[name="name"]').val(),
        description: $('textarea[name="description"]').val(),
        visibility: $('select[name="visibility"]').val()
    };
    
    if (!formData.name.trim()) {
        alert('请输入仓库名称');
        return;
    }
    
    $.ajax({
        url: '/api/repositories',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(formData),
        success: function() {
            $('#createRepoModal').modal('hide');
            $('#createRepoForm')[0].reset();
            loadRepositories();
        },
        error: function() {
            alert('创建仓库失败');
        }
    });
}

// 打开仓库详情
function openRepository(repoId, repoName) {
    currentRepoId = repoId;
    $('#repoDetailTitle').text(repoName);
    $('#repoDetailModal').modal('show');
    
    loadFiles();
    loadMembers();
}

// 加载文件列表
function loadFiles() {
    if (!currentRepoId) return;
    
    $.get(`/api/repositories/${currentRepoId}/files`, function(files) {
        const container = $('#fileList');
        container.empty();
        
        if (files.length === 0) {
            container.html('<p class="text-muted">暂无文件</p>');
            return;
        }
        
        files.forEach(file => {
            const item = createFileItem(file);
            container.append(item);
        });
    });
}

// 创建文件项
function createFileItem(file) {
    const size = formatFileSize(file.size);
    return `
        <div class="list-group-item file-item">
            <div>
                <i class="fas fa-file file-icon"></i>
                <strong>${file.name}</strong>
                <br>
                <small class="text-muted">
                    ${size} • ${new Date(file.modified).toLocaleString()}
                </small>
            </div>
            <div class="file-actions">
                <button class="btn btn-sm btn-outline-primary" onclick="downloadFile('${file.path}')">
                    <i class="fas fa-download"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteFile('${file.path}')">
                    <i class="fas fa-trash"></i>
                </button>
                <button class="btn btn-sm btn-outline-info" onclick="showHistory('${file.path}')">
                    <i class="fas fa-history"></i>
                </button>
            </div>
        </div>
    `;
}

// 处理文件上传
function handleFiles(files) {
    if (!currentRepoId) return;
    
    Array.from(files).forEach(file => {
        const formData = new FormData();
        formData.append('file', file);
        
        const progressItem = createProgressItem(file.name);
        $('#fileList').prepend(progressItem);
        
        $.ajax({
            url: `/api/repositories/${currentRepoId}/upload`,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            xhr: function() {
                const xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function(e) {
                    if (e.lengthComputable) {
                        const percent = Math.round((e.loaded * 100) / e.total);
                        updateProgress(file.name, percent);
                    }
                });
                return xhr;
            },
            success: function() {
                setTimeout(() => {
                    loadFiles();
                }, 500);
            },
            error: function() {
                alert('上传失败');
                $(`#progress-${file.name.replace(/\./g, '-')}`).remove();
            }
        });
    });
}

// 创建进度条
function createProgressItem(filename) {
    const id = `progress-${filename.replace(/\./g, '-')}`;
    return `
        <div class="list-group-item" id="${id}">
            <div class="d-flex justify-content-between align-items-center">
                <span>${filename}</span>
                <small class="text-muted">上传中...</small>
            </div>
            <div class="progress">
                <div class="progress-bar" style="width: 0%"></div>
            </div>
        </div>
    `;
}

// 更新进度条
function updateProgress(filename, percent) {
    const id = `#progress-${filename.replace(/\./g, '-')}`;
    $(id).find('.progress-bar').css('width', `${percent}%`);
    $(id).find('small').text(`${percent}%`);
}

// 下载文件
function downloadFile(filename) {
    if (!currentRepoId) return;
    window.open(`/api/repositories/${currentRepoId}/download/${filename}`);
}

// 删除文件
function deleteFile(filename) {
    if (!confirm('确定要删除这个文件吗？')) return;
    
    $.ajax({
        url: `/api/repositories/${currentRepoId}/files/${filename}`,
        method: 'DELETE',
        success: function() {
            loadFiles();
        },
        error: function() {
            alert('删除失败');
        }
    });
}

// 显示文件历史
function showHistory(filename) {
    $.get(`/api/repositories/${currentRepoId}/history/${filename}`, function(history) {
        let html = '<h6>版本历史</h6>';
        history.forEach(item => {
            html += `
                <div class="version-item">
                    <div class="d-flex justify-content-between">
                        <strong>版本 ${item.version}</strong>
                        <small>${new Date(item.created_at).toLocaleString()}</small>
                    </div>
                    <p class="mb-1">${item.message}</p>
                    <small class="text-muted">作者: ${item.author}</small>
                </div>
            `;
        });
        
        // 创建模态框显示历史
        const modal = new bootstrap.Modal(document.createElement('div'));
        modal._element.innerHTML = `
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${filename} - 版本历史</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body version-history">
                        ${html}
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal._element);
        modal.show();
    });
}

// 加载成员列表
function loadMembers() {
    if (!currentRepoId) return;
    
    $.get(`/api/repositories/${currentRepoId}/members`, function(members) {
        const container = $('#memberList');
        container.empty();
        
        if (members.length === 0) {
            container.html('<p class="text-muted">暂无成员</p>');
            return;
        }
        
        members.forEach(member => {
            const item = `
                <div class="list-group-item d-flex justify-content-between align-items-center">
                    <div>
                        <strong>${member.username}</strong>
                        <br>
                        <small class="text-muted">${member.permission}</small>
                    </div>
                    <button class="btn btn-sm btn-outline-danger" onclick="removeMember(${member.id})">
                        <i class="fas fa-user-minus"></i>
                    </button>
                </div>
            `;
            container.append(item);
        });
    });
}

// 显示添加成员模态框
function showAddMemberModal() {
    const username = prompt('请输入用户名：');
    if (!username) return;
    
    const permission = prompt('请输入权限（read/write/admin）：', 'read');
    if (!permission) return;
    
    $.ajax({
        url: `/api/repositories/${currentRepoId}/members`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({username, permission}),
        success: function() {
            loadMembers();
        },
        error: function() {
            alert('添加成员失败');
        }
    });
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
